package logic

import (
	"classtype/classtype"
	"classtype/global/model"
	"classtype/internal/svc"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type ClassTypeDeleteLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewClassTypeDeleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ClassTypeDeleteLogic {
	return &ClassTypeDeleteLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ClassTypeDeleteLogic) ClassTypeDelete(in *classtype.ClassTypeDeleteRequest) (*classtype.ClassTypeDeleteResponse, error) {
	// todo: add your logic here and delete this line
	var ClassType model.ClassTypes
	if err := model.DB.Where("parent_id = ?", in.Id).Find(&ClassType).Error; err != nil {
		return nil, err
	}
	if ClassType.ID != 0 {
		return nil, fmt.Errorf("当前分类下存在子分类，不可删除")
	}
	if err := model.DB.Where("id = ?", in.Id).Find(&ClassType).Error; err != nil {
		return nil, err
	}
	if ClassType.ID == 0 {
		return nil, nil
	}
	if err := model.DB.Delete(&ClassType).Error; err != nil {
		return nil, err
	}
	model.RDB.Del(model.Ctx, "tree")
	return &classtype.ClassTypeDeleteResponse{}, nil
}
